var intervalId = null;
var clickInterval = 10000;

// 监听来自popup的消息
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
  if (request.action === "start") {
    if (intervalId === null) {
      intervalId = setInterval(function() {
        for(let tb of document.querySelectorAll('.rpa_lc__live-goods__goods-item')[0].querySelectorAll('button')){
          if(tb.innerText == '取消讲解'){
            targetButton = tb;

            // 模拟点击
            var event = document.createEvent("MouseEvents");
            event.initMouseEvent(
              "click", true, true, window, 0,
              0, 0, 0, 0, false, false, false, false, 0, null
            );
            targetButton.dispatchEvent(event);
          }
        }

        setTimeout(function(){
          for(let tb of document.querySelectorAll('.rpa_lc__live-goods__goods-item')[0].querySelectorAll('button')){
            if(tb.innerText == '讲解'){
              targetButton = tb;

              // 模拟点击
              var event = document.createEvent("MouseEvents");
              event.initMouseEvent(
                "click", true, true, window, 0,
                0, 0, 0, 0, false, false, false, false, 0, null
              );
              targetButton.dispatchEvent(event);
            }
          }
        },2000);
      }, clickInterval);

      sendResponse({status: "自动点击已开始"});
    }
  } else if (request.action === "stop") {
    if (intervalId !== null) {
      clearInterval(intervalId);
      intervalId = null;
      sendResponse({status: "自动点击已停止"});
    }
  }
});